﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Sim
{
    public partial class PreciseQuery : Form
    {
        public PreciseQuery()
        {
            InitializeComponent();
        }

        //查询书本信息
        private void button1_Click(object sender, EventArgs e)
        {
            using (SqlConnection conn = new SqlConnection(DbHelper.connStr))//DbHelper.connStr 是连接字符串
            {
                //打开数据库连接
                conn.Open();
                string sql = "select Id,Title,Author,CreatedTime from Articles where Id ='{0}'";
                //填充SQL语句
                sql = string.Format(sql, textBox1.Text);
                //创建SqlCommand对象
                SqlCommand cmd = new SqlCommand(sql, conn);
                //定义SqlDataReader类的对象
                SqlDataReader dr = null;
                //执行Sql语句
                dr = cmd.ExecuteReader();
                //判断SQL语句是否执行成功
                if (dr.Read())
                {
                    //读取指定书名名对应的信息
                    string msg = "书号：" + dr[0] + " 文章标题：" + dr[1] + " 文章作者：" + dr[2];
                    //将msg的值显示在标签上
                    label2.Text = msg;
                }
                else if (textBox1.Text == "")
                {
                    MessageBox.Show("查询不能为空", "警告", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    string msg = "没有符合条件的结果！"; label2.Text = msg;
                }
            }
        }

        //在查询框按下Enter键即可查询
        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                button1_Click(sender, e);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
